package cn.com.lms.business.organization.web;

import cn.com.lms.business.organization.persistence.entity.FbSysDepartment;
import cn.com.lms.business.organization.service.FbSysDepartmentService;
import cn.com.lms.business.user.persistence.entity.SysUserVo;
import com.bnzj.cloud.business.core.persistence.entity.SysDepartment;
import com.bnzj.cloud.business.core.service.SysDepartmentService;
import com.bnzj.core.persistence.query.CompareExpression;
import com.bnzj.core.persistence.query.CompareType;
import com.bnzj.core.persistence.query.IExpression;

import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.persistence.util.EntityUtils;
import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.rest.ResultCode;
import cn.com.lms.business.core.util.SystemUserUtil;

import com.bnzj.cloud.business.core.persistence.entity.SysUser;
import com.bnzj.core.webmvc.util.WebMvcUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@Tag(name = "部门", description = "部门管理")
@RestController
@RequestMapping(value = "/organization/department")
public class DepartmentController {

    @Resource
    private SysDepartmentService departmentService;

    @Autowired
    private FbSysDepartmentService sysDepartmentService;

    /**
     * @return
     */
    @Operation(summary = "查询子部门", description = "查询子部门，顶级部门的ID为0")
    @GetMapping(value = "/child")
    public ResponseResult<List<SysDepartment>> getDepartmentChildList(Long id) {
        List<SysDepartment> list = departmentService.findChild(id);
        return ResponseResult.success(list);
    }

    @Operation(summary = "查询所有部门", description = "查询所有部门")
    @GetMapping(value = "/all")
    public ResponseResult<List<SysDepartment>> getAll() {
        List<SysDepartment> list = departmentService.findAll();
        return ResponseResult.success(list);
    }

    /**
     * @param pathIndex
     * @param code
     * @param name
     * @param enabled
     * @param pageable
     * @return
     */
    //@formatter:off
    @Operation(summary = "分页查询", description = "分页查询", parameters = {
            @Parameter(name = "pid", description = "父部门ID", allowEmptyValue = true,
                    schema = @Schema(implementation = Long.class)),
            @Parameter(name = "code", description = "部门编码", allowEmptyValue = true,
                    schema = @Schema(implementation = String.class, description = "部门编码")),
            @Parameter(name = "name", description = "部门名称", allowEmptyValue = true,
                    schema = @Schema(implementation = String.class, description = "部门名称")),
            @Parameter(name = "enabled", description = "部门是否启用(1启用，0禁用)", allowEmptyValue = true,
                    schema = @Schema(implementation = Boolean.class)),
    })
    //@formatter:on
    @GetMapping(value = "/page")
    public ResponseResult<Page<SysDepartment>> getDepartmentByPage(
            HttpServletRequest request,
            @RequestParam(required = false) Long pid,
            @RequestParam(required = false) String code,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Boolean enabled) {
        Pageable pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "create_time"));
        QueryHelpBean queryHelpBean = SysDepartmentService.findQueryHelpBean();
        queryHelpBean.setPageable(pageable);
        if (pid == null) {
            pid = 0L;//如果父部门ID为空则默认为顶级部门0
        }
        // 模糊查询
        IExpression expression = CompareExpression.build("e.pid", CompareType.equal, pid);
        expression.and(CompareExpression.build("d.code", CompareType.like, code),
                CompareExpression.build("d.name", CompareType.like, code));
        queryHelpBean.addWhere(expression);
        Page<SysDepartment> list = departmentService.findAll(queryHelpBean);
        return ResponseResult.success(list);
    }

    /**
     * 新增
     *
     * @param sysDepartment
     * @return
     */
    @Operation(summary = "新增")
    @PostMapping(value = "/add")
    public ResponseResult<SysDepartment> insertDepartment(@RequestBody SysDepartment sysDepartment) {
        SysUserVo currentUser = SystemUserUtil.getCurrentUser();
        EntityUtils.saveBefore(sysDepartment, currentUser.getCname(), currentUser.getAccount());
        SysDepartment department = departmentService.save(sysDepartment);
        return ResponseResult.success(department);
    }

    /**
     * @param id
     * @return
     */

    @Operation(summary = "根据ID删除")
    @GetMapping(value = "/delete/{id}")
    public ResponseResult<String> deleteById(@PathVariable Long id) {
        departmentService.delete(id);
        return ResponseResult.success();
    }

    /**
     * @param ids
     * @return
     */
    @Operation(summary = "根据ID批量删除")
    @PostMapping(value = "/deleteByIds")
    public ResponseResult<String> deleteByIds(@RequestBody Long[] ids) {
        departmentService.deleteAll(Arrays.asList(ids));
        return ResponseResult.success();
    }

    /**
     * @param sysDepartment
     * @return
     */
    @Operation(summary = "修改")
    @PostMapping(value = "/edit")
    public ResponseResult<SysDepartment> editDepartment(@RequestBody SysDepartment sysDepartment) {
        if (ObjectUtils.isEmpty(sysDepartment.getId())) {
            return ResponseResult.failure(ResultCode.FAILURE, sysDepartment);
        }
        sysDepartment = departmentService.save(sysDepartment);
        return ResponseResult.success(sysDepartment);
    }


    @Operation(summary = "获取部门树节点", description = "")
    @GetMapping("/getDeptTreeList")
    public ResponseResult<List<FbSysDepartment>> getDeptTreeList() {
        return ResponseResult.success(sysDepartmentService.getDeptTreeList());
    }
}
